<template>
  <div class="boxs">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="文件名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="small" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button><el-button
          icon="el-icon-plus" type="primary" plain size="small" @click="openDialog">添加知识文件</el-button>
      </el-form-item>
    </el-form>


    <el-table :data="userArr" style="width: 100%" v-loading="loading">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="文件名称" align="center" prop="name" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="存放路径" align="center" prop="url" />
      <el-table-column label="创建时间" align="center" prop="create_time" />

      <el-table-column label="操作" align="center" width="350">
        <template slot-scope="scope">
          <el-button size="mini" v-if="scope.row.admin !== 1"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" v-if="scope.row.admin !== 1" type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
      @pagination="getZsglList" />

    <el-dialog title="操作框" :visible.sync="dialogVisible" width="40%">
      <el-form class="demo-form-inline" label-width="80px" :model="form" ref="ruleForm">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件名称" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注">
          </el-input>
        </el-form-item>

        <el-form-item label="文件上传">
          <el-upload name="images" ref="upload" class="upload-demo" action="" list-type="picture-card"
            :file-list="fileList" :on-remove="handleRemove" :on-change="handleChange"
            :before-upload="beforeUpload" :auto-upload="false" :limit="1" :on-exceed="handleExceed">
            <i class="el-icon-plus"></i> <!-- 上传按钮 -->
          </el-upload>

          <!-- 图片预览 -->
          <el-dialog :visible.sync="previewDialogVisible">
            <img width="100%" :src="previewImage" alt="preview" />
          </el-dialog>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer" v-loading="addLoading">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="form.id ? 'warning' : 'primary'" @click="affirm">{{
          form.id ? "确认修改" : "确认添加"
        }}</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>
import { getZsglList, addZsgl, delZsgl, addFile, upZsgl } from '@/api/admin';
import { formatDate } from "@/utils";

export default {
  name: "Zsgl",
  data() {
    return {
      // editorContent: '', // 富文本内容绑定的数据
      queryParams: {
        page: 1,
        size: 10
      },
      total: 0,
      loading: false,
      addLoading: false,
      userArr: [],
      dialogVisible: false,
      themeOpen: false,
      rolesArr: [],
      moreArr: [],
      fqArr: [],
      search: '',
      form: {
        rxbz: '',
      },
    }
  },
  components: {
    // quillEditor,
  },
  async created() {
    this.getZsglList()
  },
  methods: {
    formatterCreateTime(row) {
      return formatDate(row.createTime);
    },
    formatMore(row) {
      if (row.admin === 1) return "总管理";
      let res = this.moreArr.filter(t => t.id == row.moreId);
      if (res.length == 0) return "“账号不存在”"
      return res[0].name
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await delZsgl({ id: row.id });
        this.getZsglList();
        this.$message({
          message: '删除成功！',
          type: 'success'
        });
      })
    },
    resetForm() {
      this.form = {};
    },
    handleEdit(index, row) {
      this.resetForm();
      this.form = { ...row };
      // this.$set(this.form, "rolesId", row.rolesId.split(","));
      this.dialogVisible = true;
    },
    async affirm() {
      try {

        this.addLoading = true;
        if (!this.form.id) {
          if (this.fileList.length === 0) {
            this.$message.error('请上传文件');
            this.addLoading = false;
            return;
          }
          let ret = await addZsgl({ ...this.form });
          if (ret.code == 1) {
            this.$message.success('添加成功！');
            if (this.fileList && this.fileList.length > 0) {
              const formData = new FormData();
              this.fileList.forEach(file => {
                formData.append('images', file.raw); // 'images' 是后端接收文件的字段名
              });
              formData.append('id', ret.data.insertId); // 添加知识文件ID
              const r = await addFile(formData);
              this.$message.success(r.msg);
            }
          }

        } else {
          let ret = await upZsgl({ ...this.form });
          if (ret.code == 1) {
            this.$message.success('修改成功！');
            this.fileList = [];
          }
        }
        this.addLoading = false;
        this.getZsglList();
        this.dialogVisible = false;

      } catch (e) {
        console.log(e);
        this.addLoading = false;
        this.getZsglList();
        this.dialogVisible = false;
      }

    },

    openDialog() {
      this.resetForm();
      this.dialogVisible = true;
      // 清空文件上传列表
      this.fileList = [];
    },

    async getZsglList() {
      this.loading = true;
      const { data, total } = await getZsglList(this.queryParams);
      this.loading = false;
      this.userArr = data; this.total = total;
    },
    handleQuery() {
      this.queryParams.page = 1;
      this.getZsglList();
    },




    // 图片操作
    // 预览图片
    handlePreview(file) {
      this.previewImage = file.url || file.raw;
      this.previewDialogVisible = true;
    },
    // 上传前校验
    beforeUpload(file) {
      const realFile = file.raw || file;
      const isLt20M = realFile.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!');
      }
      const isImage = realFile.type === 'image/jpeg' || realFile.type === 'image/png' || realFile.type === 'application/pdf';
      if (!isImage) {
        this.$message.error('仅支持 JPG/PNG 和 pdf 格式!');
      }
      return isLt20M && isImage;
    },

    // 文件删除回调
    handleRemove(file, fileList) {
      this.fileList = fileList; // 更新文件列表
    },
    // 文件选择回调
    handleChange(file, fileList) {
      // 只保留最后一个文件
      if (fileList.length > 1) {
        fileList.splice(0, fileList.length - 1);
      }
      // 兼容 file.raw
      const realFile = file.raw || file;
      const isImage = realFile.type === 'image/jpeg' || realFile.type === 'image/png' || realFile.type === 'application/pdf';
      const isLt20M = realFile.size / 1024 / 1024 < 20;
      if (!isImage) {
        this.$message.error('仅支持 JPG/PNG 和 pdf 格式!');
        fileList.pop();
      } else if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!');
        fileList.pop();
      }
      this.fileList = fileList;
    },
    // 删除图片
    // async deleteImage(img, index) {
    //   try {
    //     await delPic({ id: img.id });
    //     this.$message.success('删除图片成功');
    //     let nodedata = await getJcsNode({ id: this.editForm.id });
    //     this.editForm = nodedata.data;
    //     this.imageList = nodedata.data.images;
    //   } catch (error) {
    //     console.error('删除图片失败:', error, index);
    //     this.$message.error('删除图片失败');
    //   }
    // }
    handleExceed(files, fileList) {
      console.log(files, fileList);
      this.$message.warning('最多只能上传1个文件');
    }

  }
}
</script>
<style scoped lang="scss">
.boxs {
  padding: 20px;
}

.color-title {
  margin-bottom: 10px;
  color: #000;
}
</style>
